<template>
  <div class="personnel-container flex-column">
    <custom-button @click="addRole" title="新增"></custom-button>
    <div class="flex-sub table-container">
      <el-table
        :data="tableData"
        v-loading="tableLoading"
        header-cell-class-name="table-header-cell"
        header-row-class-name="table-header-row"
        height="98%"
      >
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="remark" label="说明" />
        <el-table-column prop="sceneVo.name" label="产品应用" />
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createTime | dateTimeFormatter }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime | dateTimeFormatter }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          :width="handleScreenWidthToVw(290)+'px'"
          align="center"
        >
          <div slot-scope="scope" class="justify-end align-center  action-bar">
            <div class="flex-row">
              <span @click="handleAddUser(scope.row)" class="add-user-button">添加用户</span>
              <el-dropdown
                trigger="click"
                class="update-button"
                @command="handleCommand($event, scope.row)"
              >
                <span style="color: #409eff;">
                  修改
                  <i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="role">角色属性</el-dropdown-item>
                  <el-dropdown-item command="menu">菜单权限</el-dropdown-item>
                  <el-dropdown-item command="copyRole">复制角色</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <div class="btn-delete" @click="delRole(scope.row.id)">删除</div>
            </div>
          </div>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-pagination
      background
      hide-on-single-page
      layout="prev, pager, next, total, jumper"
      :current-page="page.pageNo"
      :page-size="page.pageSize"
      :total="page.total"
      @current-change="handleCurrentChange"
    />
    <!-- 角色弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible.addRole"
      :width="handleScreenWidthToVw(500)+'px'"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="Rules"
        :label-width="handleScreenWidthToVw(100)+'px'"
        style="text-align: left;"
        ref="roleForm"
      >
        <el-form-item label="角色名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="场景:">
          <el-select v-model="form.sceneId" placeholder="请选择">
            <el-option
              v-for="(item, index) in productList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="说明:">
          <el-input v-model="form.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <SubButton v-if="!isUpdate" @subClick="subFrom" />
        <SubButton v-else @subClick="updateRole" />
        <CancelButton @cancelClick="cancel" />
      </div>
    </el-dialog>
    <!-- 用户弹窗 -->
    <UserSelector
      ref="userSelector"
      :selectedUsersList="selectedUsersList"
      :selectedNum="selectedNum"
      :userVisible="isUserVisible"
      @openClick="handleAddUser(scope.row)"
      @confirmClick="addRoleUser"
      @cancelClick="cancelUser"
    />
    <!-- 菜单弹窗 -->
    <el-dialog
      title="菜单权限"
      :visible.sync="isMenuVisible"
      :width="handleScreenWidthToVw(574)+'px'"
      :modal-append-to-body="false"
      :show-close="false"
      :before-close="() => $emit('before-close')"
    >
      <SelectMenu ref="selectMenu" :selected-menu-list="defaultMenu" />
      <div slot="footer" class="dialog-footer">
        <SubButton title="确定" @subClick="subMenu" />
        <CancelButton @cancelClick="cancelMenu" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRolelist,
  delRoleList,
  updateRoleList,
  updateRoleMenu,
  addRolelist,
  updateRoleUser,
  copyRoleList,
  getProductList,
  findRoleById,
} from './api'
import SubButton from '@/components/sub-button/index.vue'
import CancelButton from '@/components/cancel-button/index.vue'
import UserSelector from '@/components/user-selector/index.vue'
import { handleScreenWidthToVw } from '@/utils/tools'
import SelectMenu from '@/components/select-menu/index.vue'

export default {
  components: {
    SubButton,
    CancelButton,
    SelectMenu,
    UserSelector,
  },

  data() {
    return {
      tableLoading: false,
      isOpen: true,
      isUpdate: false,
      isMenuVisible: false,
      isUserVisible: false,
      title: '',
      roleId: '',
      selectedNum: 0,
      selectedUsersList: [],
      dialogVisible: {
        addRole: false,
      },
      form: { name: '', remark: '', sceneId: '' },
      tableData: [],
      defaultMenu: [],
      productList: [],
      page: {
        pageNo: 1,
        pageSize: 14,
        total: null,
      },
    }
  },
  computed: {
    handleScreenWidthToVw() {
      return handleScreenWidthToVw
    },
    Rules() {
      return {
        name: [{ required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }],
      }
    },
  },
  created() {
    this.getData()
  },
  methods: {
    // 重置菜单权限表单
    cancelMenu() {
      this.isMenuVisible = false
      this.defaultMenu = []
    },
    // 切换页面
    handleCurrentChange(val) {
      this.page.pageNo = val
      this.getData(this.page)
    },
    // 重置用户表单
    cancelUser() {
      this.selectedUsersList = []
      this.isUserVisible = false
    },
    // 取消表单
    async cancel() {
      this.dialogVisible.addRole = false
      this.resetForm()
    },
    // 重置表单
    resetForm() {
      this.form = { name: '', remark: '', sceneId: '', initRole: false }
      this.$nextTick(() => {
        this.$refs.roleForm.clearValidate()
      })
    },
    // 提交菜单权限
    async subMenu() {
      this.form.roleMenus = this.$refs.selectMenu.getMenuList()
      await updateRoleMenu(this.form)
      this.getData()
      this.isMenuVisible = false
      this.$message({
        type: 'success',
        message: '提交成功!',
      })
    },
    // 激活菜单权限弹窗
    async changeMenu(user) {
      this.form = user
      this.defaultMenu = user.roleMenus ? user.roleMenus : []
      this.isMenuVisible = true
    },
    // 提交绑定角色的用户
    async addRoleUser() {
      const roleUsers = await this.$refs.userSelector.getUsersList()
      const roleUserFrom = { id: this.roleId, roleUsers }
      await updateRoleUser(roleUserFrom)
      console.log(roleUserFrom)
      this.getData()
      this.$message({
        type: 'success',
        message: '绑定成功!',
      })
      this.isUserVisible = false
    },
    // 点击添加用户按钮
    async handleAddUser(role) {
      const { roleUsers } = await findRoleById(role.id)
      roleUsers ? (this.selectedUsersList = roleUsers) : []
      this.selectedNum = roleUsers ? roleUsers.length : 0
      this.roleId = role.id
      this.isUserVisible = true
    },
    // 提交修改角色基本信息
    async updateRole() {
      await updateRoleList(this.form)
      this.resetForm()
      this.getData()
      this.dialogVisible.addRole = false
      this.$message({
        type: 'success',
        message: '修改成功!',
      })
    },
    // 点击编辑下拉框
    handleCommand(command, obj) {
      if (command === 'role') {
        this.changeRole(obj)
      } else if (command === 'menu') {
        this.changeMenu(obj)
      } else if (command === 'copyRole') {
        this.copyRole(obj.id)
      }
    },
    // 复制角色
    async copyRole(roleId) {
      this.$confirm('确定复制已选中的对象吗, 是否继续?', '复制角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success',
      })
        .then(() => {
          copyRoleList(roleId).then(() => {
            this.getData()
            this.$message({
              type: 'success',
              message: '复制成功!',
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消复制',
          })
        })
    },
    // 修改角色按钮
    async changeRole(role) {
      this.isUpdate = true
      this.title = '修改角色'
      this.form = Object.assign(this.form, role)

      this.productList = await getProductList()
      this.dialogVisible.addRole = true
    },
    // 添加角色按钮
    async addRole() {
      this.title = '新增角色'
      this.isUpdate = false
      this.productList = await getProductList()
      this.resetForm()
      this.dialogVisible.addRole = true
    },
    // 删除角色
    delRole(roleId) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delRoleList(roleId).then(() => {
            this.getData()
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 获取数据
    getData() {
      this.tableLoading = true
      getRolelist(this.page)
        .then(Res => {
          this.tableData = Res.records
          this.page.total = Res.total
        })
        .finally(() => (this.tableLoading = false))
    },
    // 提交
    async subFrom() {
      await this.$refs.roleForm.validate()
      addRolelist(this.form).then(() => {
        this.resetForm()
        this.getData()
        this.dialogVisible.addRole = false
        this.$message({
          type: 'success',
          message: '添加成功!',
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.personnel-container {
  width: 100%;
  height: 100%;
  padding: vh(20px) vw(20px);
  background: #fff;
  box-sizing: border-box;
}

.query-container {
  display: flex;
  flex-direction: row;
}

.custom-button {
  margin-bottom: vh(20px);
}

.add-user-button {
  padding: 0 vw(10px);
  font-size: vw(12px);
  line-height: vh(26px);
  color: #0084ee;
  cursor: pointer;
  border: 1px solid #0084ee;
  border-radius: 4px;
}

.update-button {
  height: vh(30px);
  padding: 0 vw(10px);
  font-size: vw(12px);
  line-height: vh(28px);
  color: #0084ee;
  cursor: pointer;
  border: 1px solid #0084ee;
  border-radius: 4px;
}

.add-user-button + .update-button {
  margin-left: vw(10px);
}

.btn-delete {
  padding-left: vw(10px);
  line-height: vh(28px);
  color: #d12d1f;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

.action-bar {
  padding-right: vw(20px);
}

.add-user-title {
  padding: 0 vh(20px);

  span {
    font-size: vw(14px);
  }
}

.menu-title {
  font-size: vw(16px);
  font-weight: 400;
  color: #666;
  text-align: left;
}

.menu-list {
  div {
    text-align: center;
  }
}

::v-deep {
  .el-message-box__headerbtn {
    color: #000 !important;
  }

  .el-dialog__header {
    height: vh(52px);
    padding: vw(17px) vh(23px) vw(17px);
  }

  .el-dialog__title {
    font-size: vw(18px);
    font-weight: 500;
    color: #333;
  }

  .el-dialog__footer {
    padding: vh(10px) vw(20px) vh(20px);
    text-align: center;
  }

  .el-dialog__body {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    padding: vh(20px);
  }

  .el-form-item__label,
  .el-form-item__content {
    font-size: vw(12px);
    line-height: vh(40px);
  }

  .el-form-item {
    margin-bottom: vh(22px);
  }

  .el-input__inner {
    width: vw(250px);
  }

  .el-pagination__editor {
    .el_input {
      width: vw(51px);
    }

    .el-input__inner {
      width: vw(30px);
    }
  }

  .el-table td,
  .el-table th {
    padding-left: vw(20px);
  }
}
</style>
